const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 确保terser可用，使用内联方式实现简单压缩
function minifyJavaScript(code) {
  // 简单的压缩实现（实际项目中可以替换为完整的terser逻辑）
  // 移除注释
  code = code.replace(/\/\*[\s\S]*?\*\//g, '');
  code = code.replace(/\/\/.*$/gm, '');
  // 移除多余空格
  code = code.replace(/\s+/g, ' ');
  code = code.replace(/\s*{\s*/g, '{');
  code = code.replace(/\s*}\s*/g, '}');
  code = code.replace(/\s*;\s*/g, ';');
  code = code.replace(/\s*,\s*/g, ',');
  code = code.replace(/\s*:\s*/g, ':');
  code = code.replace(/\s*\(\s*/g, '(');
  code = code.replace(/\s*\)\s*/g, ')');
  code = code.replace(/\s*\+\s*/g, '+');
  code = code.replace(/\s*-\s*/g, '-');
  code = code.replace(/\s*\*\s*/g, '*');
  code = code.replace(/\s*\/\s*/g, '/');
  
  return code;
}

// 递归遍历目录
function walkDir(dir, callback) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const fullPath = path.join(dir, file);
    const stats = fs.statSync(fullPath);
    if (stats.isDirectory()) {
      walkDir(fullPath, callback);
    } else {
      callback(fullPath);
    }
  });
}

console.log('开始构建...');

// 1. 首先运行tsc编译TypeScript
console.log('执行TypeScript编译...');
try {
  execSync('npx tsc', { stdio: 'inherit' });
  console.log('TypeScript编译成功');
} catch (error) {
  console.error('TypeScript编译失败:', error);
  process.exit(1);
}

// 2. 压缩JavaScript文件
const distDir = path.join(__dirname, 'dist');
console.log('开始压缩JavaScript文件...');

walkDir(distDir, (filePath) => {
  if (filePath.endsWith('.js') && !filePath.endsWith('.d.ts')) {
    try {
      const originalCode = fs.readFileSync(filePath, 'utf8');
      const minifiedCode = minifyJavaScript(originalCode);
      
      // 保存压缩后的代码
      fs.writeFileSync(filePath, minifiedCode, 'utf8');
      
      const originalSize = originalCode.length;
      const minifiedSize = minifiedCode.length;
      const reduction = ((originalSize - minifiedSize) / originalSize * 100).toFixed(2);
      
      console.log(`压缩 ${path.relative(distDir, filePath)}: ${originalSize} -> ${minifiedSize} (减少${reduction}%)`);
    } catch (error) {
      console.error(`压缩文件失败 ${filePath}:`, error);
    }
  }
});

console.log('构建完成！');
